package cn.edu.huanu.utils;

import cn.edu.huanu.exception.DaoException;

import java.sql.*;

/**
 *
 * 提供获得Connection对象的工具类
 * @author hb
 * @date 2025-10-17 15:06:16
 */
public class ConnectionUtils {
    private static String username ="root";
    private static String password="root";
    private static String url="jdbc:mysql://localhost:3306/test";
    private static String driverClass="com.mysql.cj.jdbc.Driver";


    //在静态块中加载驱动
    static{
        try {
            Class.forName(driverClass);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            throw new DaoException(e.getMessage());
        }
    }

    /**
     * 获得一个新的Connection对象
     * @return
     */
    public static Connection newConnection(){
        Connection conn=null;
        try {
            conn= DriverManager.getConnection(url,username,password);
            return conn;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 释放Connection对象
     *
     * Connection对象为物理资源必须手动释放，GC无法自动回收
     * @param conn
     */
    public static void close(Connection conn){
          close(conn,null,null);
    }

    public static void close(Connection conn, PreparedStatement pstm){
        close(conn,pstm,null);
    }

    public static void close(Connection conn, PreparedStatement pstm, ResultSet rs){

        try {
        if(rs!=null){
            rs.close();
        }

        if(pstm!=null){
            pstm.close();
        }
         if(conn!=null){
           conn.close();
         }
        } catch (SQLException e) {
            throw new DaoException(e);
        }
    }
}
